﻿
using AmazonMODEL;
using MarketplaceWebService;
using MarketplaceWebService.Model;
using MODEL;
using Newtonsoft.Json;
using SysCommon;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SysController
{
    /// <summary>
    /// 1.0  提交处理
    /// </summary>
    public static partial class FeedsController
    {
        #region 1.0 信息提交 + static FeedsInfo SubmitFeed(AppModel appkey, FeedsInfo model)
        /// <summary>
        /// 1.0 信息提交
        /// </summary> 
        public static FeedsInfo SubmitFeed(AppKey appkey, FeedsInfo model)
        {
            MarketplaceWebService.Model.SubmitFeedRequest request = new MarketplaceWebService.Model.SubmitFeedRequest()
            {
                MarketplaceIdList = new MarketplaceWebService.Model.IdList() { Id = new List<string>() { appkey.MarketplaceCode } },
                Merchant = appkey.MerchantCode,
                FeedContent = new MemoryStream(Encoding.ASCII.GetBytes(model.AmazonEnvelope)),
                FeedType = model.FeedType
            };
            request.ContentMD5 = MarketplaceWebService.MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            try
            {
                MarketplaceWebService.Model.SubmitFeedResponse response = HelperController.RegisterFeedsService(appkey).SubmitFeed(request);
                string submitStr = JsonConvert.SerializeObject(response);
                if (response.SubmitFeedResult.IsSetFeedSubmissionInfo())
                {
                    FeedSubmissionInfo info = response.SubmitFeedResult.FeedSubmissionInfo;
                    model.CompletedProcessingDate = info.CompletedProcessingDate.ToString();
                    model.FeedProcessingStatus = info.FeedProcessingStatus;
                    model.FeedSubmissionId = info.FeedSubmissionId;
                    model.FeedType = info.FeedType;
                    model.StartedProcessingDate = info.StartedProcessingDate.ToString();
                    model.SubmittedDate = info.SubmittedDate;
                    model.ResultData = submitStr;
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = "FeedsInfoSubmit";
                    model.IsDel = false;
                    return model;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                //TODO:
                return null;
            }
        }
        #endregion

        #region 2.0 信息提交获取 + static List<FeedsInfo> GetFeedSubmissionList(AppModel appkey, List<FeedsInfo> list)
        /// <summary>
        /// 2.0 信息提交获取
        /// </summary>
        public static List<FeedsInfo> GetFeedSubmissionList(AppKey appkey, List<FeedsInfo> list, string feedType = null)
        {
            GetFeedSubmissionListRequest request = new GetFeedSubmissionListRequest()
            {
                Marketplace = appkey.MarketplaceCode,
                Merchant = appkey.MerchantCode,
                FeedTypeList = feedType != null
                ? new TypeList() { Type = new List<string>() { feedType } }
                : new TypeList()
                {
                    Type = new List<string>() { 
                      FeedType._POST_PRODUCT_DATA_.ToString(),
                      FeedType._POST_INVENTORY_AVAILABILITY_DATA_.ToString(),
                      FeedType._POST_PRODUCT_IMAGE_DATA_.ToString(),
                      FeedType._POST_PRODUCT_PRICING_DATA_.ToString(),
                      FeedType._POST_PRODUCT_RELATIONSHIP_DATA_.ToString() 
                  }
                },
                FeedSubmissionIdList = new IdList() { Id = new List<string>() },
                FeedProcessingStatusList = new MarketplaceWebService.Model.StatusList() { Status = new List<string>() { "_DONE_" } },
                MaxCount = 100
            };
            request.FeedSubmissionIdList.Id = list.Select(s => s.FeedSubmissionId).ToList();
            try
            {
                GetFeedSubmissionListResponse response = HelperController.RegisterFeedsService(appkey).GetFeedSubmissionList(request);
                if (response.GetFeedSubmissionListResult.IsSetFeedSubmissionInfo())
                {
                    string submitStr = JsonConvert.SerializeObject(response);
                    List<FeedSubmissionInfo> infoList = response.GetFeedSubmissionListResult.FeedSubmissionInfo;
                    List<FeedsInfo> ls = new List<FeedsInfo>();
                    foreach (var info in infoList)
                    {
                        FeedsInfo model = list.Where(s => s.FeedSubmissionId == info.FeedSubmissionId).FirstOrDefault();
                        if (model == null)
                            continue;
                        model.CompletedProcessingDate = info.CompletedProcessingDate.ToString();
                        model.FeedProcessingStatus = info.FeedProcessingStatus;
                        model.FeedSubmissionId = info.FeedSubmissionId;
                        model.FeedType = info.FeedType;
                        model.StartedProcessingDate = info.StartedProcessingDate.ToString();
                        model.SubmittedDate = info.SubmittedDate;
                        model.ResultData = submitStr;
                        model.UpdateTime = DateTime.Now;
                        model.UpdateUser = "SubmitFeedStatus";
                        model.IsDel = false;
                        ls.Add(model);
                    }
                    return ls;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 3.0 提交处理结果获取 +  static FeedsInfo GetFeedSubmissionResult(AppModel appkey, FeedsInfo model)
        /// <summary>
        /// 3.0 信息提交处理结果获取
        /// </summary>
        public static FeedsInfo GetFeedSubmissionResult(AppKey appkey, FeedsInfo model)
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["FeedsFilePath"];
            MarketplaceWebService.Model.GetFeedSubmissionResultRequest request = new MarketplaceWebService.Model.GetFeedSubmissionResultRequest()
            {
                Marketplace = appkey.MarketplaceCode,
                Merchant = appkey.MerchantCode,
                FeedSubmissionId = model.FeedSubmissionId,
                FeedSubmissionResult = File.Open(string.Format(@"{0}\{1}.txt", path, model.FeedSubmissionId), FileMode.OpenOrCreate, FileAccess.ReadWrite)
            };
            try
            {
                MarketplaceWebService.Model.GetFeedSubmissionResultResponse response = HelperController.RegisterFeedsService(appkey).GetFeedSubmissionResult(request);
                request.FeedSubmissionResult.Close();
                using (StreamReader reader = File.OpenText(string.Format(@"{0}\{1}.txt", path, model.FeedSubmissionId)))
                {
                    model.ResultData = reader.ReadToEnd();
                    reader.Dispose();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                return null;
            }
            return model;
        }
        #endregion
    }

    public static partial class FeedsController
    {
        public static void SubmitFeed(AppKey appkey, AmazonEnvelope ae)
        {
            MarketplaceWebService.Model.SubmitFeedRequest request = new MarketplaceWebService.Model.SubmitFeedRequest()
          {
              MarketplaceIdList = new MarketplaceWebService.Model.IdList() { Id = new List<string>() { appkey.MarketplaceCode } },
              Merchant = appkey.MerchantCode,
              FeedContent = new MemoryStream(Encoding.ASCII.GetBytes(SysCommon.XmlHelper.ObjectToXmlSerializer(ae))),
              FeedType = "_POST_ORDER_FULFILLMENT_DATA_"
          };
            request.ContentMD5 = MarketplaceWebService.MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            try
            {
                MarketplaceWebService.Model.SubmitFeedResponse response = HelperController.RegisterFeedsService(appkey).SubmitFeed(request);
                string submitStr = JsonConvert.SerializeObject(response);
            }
            catch (Exception)
            {

            }
        }
    }

    public static partial class FeedsController
    {
        public static void SubmitFeed(AppKey appkey, string feedType, string filePath)
        {
            MarketplaceWebService.Model.SubmitFeedRequest request = new MarketplaceWebService.Model.SubmitFeedRequest()
            {
                MarketplaceIdList = new MarketplaceWebService.Model.IdList() { Id = new List<string>() { appkey.MarketplaceCode } },
                Merchant = appkey.MerchantCode,
                FeedContent = File.Open(filePath, FileMode.Open, FileAccess.Read),
                FeedType = feedType
            };
            request.ContentMD5 = MarketplaceWebService.MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            try
            {
                MarketplaceWebService.Model.SubmitFeedResponse response = HelperController.RegisterFeedsService(appkey).SubmitFeed(request);
                if (response.SubmitFeedResult.IsSetFeedSubmissionInfo())
                {
                    FeedSubmissionInfo info = response.SubmitFeedResult.FeedSubmissionInfo;
                    //info.FeedSubmissionId
                    //info.FeedType
                    //info.FeedProcessingStatus
                    //info.CompletedProcessingDate 
                }
            }
            catch (Exception ex)
            {
                SysCommon.Log.Log.WriteError(ex, "SubmitFeed Exception");
            }
        }
    }



    public static partial class FeedsController
    {
        public static Feed SubmitFeed(AppKey appkey, Feed feed)
        {
            MarketplaceWebService.Model.SubmitFeedRequest request = new MarketplaceWebService.Model.SubmitFeedRequest()
            {
                MarketplaceIdList = new MarketplaceWebService.Model.IdList() { Id = new List<string>() { appkey.MarketplaceCode } },
                Merchant = appkey.MerchantCode,
                FeedContent = File.Open(feed.UploadPath, FileMode.Open, FileAccess.Read),
                FeedType = feed.FeedType
            };
            request.ContentMD5 = MarketplaceWebService.MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            try
            {
                MarketplaceWebService.Model.SubmitFeedResponse response = HelperController.RegisterFeedsService(appkey).SubmitFeed(request);
                string submitStr = JsonConvert.SerializeObject(response);
                if (!response.SubmitFeedResult.IsSetFeedSubmissionInfo())
                {
                    SysCommon.Log.Log.Write("IsSetFeedSubmissionInfo false");
                    return null;
                }
                FeedSubmissionInfo info = response.SubmitFeedResult.FeedSubmissionInfo;
                feed.FeedSubmissionId = info.FeedSubmissionId;
                feed.Intervals = 0;
                feed.UpdateTime = DateTime.Now;
                feed.UpdateUser = "AutoSubmit";
                feed.IsDel = false;
                return feed;
            }
            catch (Exception ex)
            {
                SysCommon.Log.Log.WriteError(ex, "AutoSubmit SubmitFeed 异常");
                return null;
            }
        }

        public static Feed GetFeedSubmissionResult(AppKey appkey, Feed feed)
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["FeedsFilePath"];
            path = string.Format(@"{0}\{1}_Download.xml", path, feed.FeedsName);

            MarketplaceWebService.Model.GetFeedSubmissionResultRequest request = new MarketplaceWebService.Model.GetFeedSubmissionResultRequest()
            {
                Marketplace = appkey.MarketplaceCode,
                Merchant = appkey.MerchantCode,
                FeedSubmissionId = feed.FeedSubmissionId,
                FeedSubmissionResult = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)
            };
            try
            {
                MarketplaceWebService.Model.GetFeedSubmissionResultResponse response = HelperController.RegisterFeedsService(appkey).GetFeedSubmissionResult(request);
                request.FeedSubmissionResult.Close();
                feed.Intervals = 1;
                feed.UpdateUser = "GetFeedResult";
                feed.UpdateTime = DateTime.Now;
                return feed;  
            }
            catch (Exception ex)
            {
                SysCommon.Log.Log.WriteError(ex, "GetFeedResult 异常");
                return null;
            } 
        } 
        
        //using (StreamReader reader = File.OpenText(string.Format(@"{0}\{1}_Download.xml", path, feed.FeedsName)))
        //{
        //    //model.ResultData = reader.ReadToEnd();
        //    reader.Dispose();
        //    reader.Close();
        //}
    }


}

